package cn.concurrence.productconsume;

/**
 *
 * 使用synchronized wait notify
 *
 * @author summit
 * @since 2022/4/25 11:24
 */
public class ProdConsTest1 {

	private Integer num = 0;

	synchronized void increment() throws InterruptedException {
		if (num != 0) {
			this.wait();
		}
		num++;
		System.out.println(Thread.currentThread().getName() + ":" + num);

		// 唤醒所有
		this.notifyAll();
	}

	synchronized void decrement() throws InterruptedException {
		if (num == 0) {
			this.wait();
		}
		num--;
		System.out.println(Thread.currentThread().getName() + ":" + num);

		// 唤醒所有
		this.notifyAll();
	}

	public static void main(String[] args) {
		ProdConsTest1 prodConsTest1 = new ProdConsTest1();

		new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				try {
					prodConsTest1.increment();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}).start();


		new Thread(() -> {
			for (int i = 0; i < 10; i++) {
				try {
					prodConsTest1.decrement();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}

		}).start();
	}
}
